import React, { Component } from "react";
import "./index.less";
import { formateDate } from "../../utils/dateUtils";
import memoryUtils from "../../utils/memoryUtils";
import { withRouter } from "react-router-dom";
import { Modal } from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import storageUtils from "../../utils/storageUtils";
import LinkButton from "../link-button";

const { confirm } = Modal;
class Header extends Component {
  state = {
    currentTime: formateDate(Date.now()), //当前时间
    text: "",
  };

  getTime = () => {
    this.intervalId = setInterval(() => {
      // 每个1s获取时间，更新currentime
      const currentTime = formateDate(Date.now());
      this.setState({ currentTime });
    }, 1000);
  };

  logout = () => {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: "是否退出",
      onOk: () => {
        //删除保存的user数据
        // 删除本地
        storageUtils.removeUser();
        //删除内存
        memoryUtils.user = {};
        //跳转登录页面
        this.props.history.replace("/login");
      },
    });
  };

  componentDidMount() {
    this.getTime(); //获取当前时间
  }

  // 当前组件卸载之前使用
  componentWillUnmount() {
    //清除定时器
    clearInterval(this.intervalId);
  }
  render() {
    const { currentTime, text } = this.state;
    const user = memoryUtils.user.username;
    const title = memoryUtils.title;
    return (
      <div className="header">
        <div className="header-top">
          <span>欢迎,{user}</span>
          <LinkButton onClick={this.logout}>退出</LinkButton>
        </div>
        <div className="header-bottom">
          <div className="header-bottom-left">{title}</div>
          <div className="header-bottom-right">
            <span>{currentTime}</span>
            <img
              src="http://api.map.baidu.com/images/weather/day/qing.png"
              alt="weather"
            ></img>
            <span>{text}</span>
          </div>
        </div>
      </div>
    );
  }
}
export default withRouter(Header);
